<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="https://cdn.jsdelivr.net/npm/echarts@5.3.2/dist/echarts.min.js"></script>
		<style> html, body, #app { height: 100%; } </style>
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<script src="js/vue.min.js"></script>
		<script src="js/axios.min.js"></script>
		<script src="https://unpkg.com/element-ui/lib/index.js"></script>
	</head>
	<body>
		<div id="app" style="display: flex; flex-direction: column; width: 90%; margin:auto; height: calc(100% - 50px)">
			<h4 style="flex: none;display: flex; align-items: center; justify-content: space-between">
				历年同月销量柱状图
				<form style="display: flex; align-items: center; font-weight: normal;">
					<span v-for="year in yearItems">
						<input type="checkbox" :value="year" v-model="years">{{year}}年
					</span>

					<select v-model="month" @change="query" style="width: 50px;margin-left: 20px">
						<option v-for=" m in 12 " :value='m < 10 ? "0" + m : m'>
							{{ m < 10 ? "0" + m : m }}月
						</option>
					</select>
				</form>
			</h4>
			<div id="container" style="flex:auto"></div>
		</div>
		<script type="text/javascript">
			var v = new Vue({
				el : "#app",
				data : {
					years : [],		 // 选择的年份数组
					yearItems : [],  // 选项数组
					month : "01",
					sales : [],
					queryYears : []	 // 查询到的年份
				},
				created(){
					axios.get("years.s").then(res=>{
						this.yearItems = res.data.map( row=>row.year );
						// 默认选择所有的年份
						this.years = res.data.map( row=>row.year );
						this.query();
					})
				},
				methods : {
					query(){
						var url = "zzt.s?";
						this.years.forEach(year=>{
							url += "year=" + year + "&";
						});
						url += "month=" + this.month;
						axios.get(url).then(res=>{
							this.sales = res.data.map( row=>row.sale );
							// 把查询到的年份保存到数组中
							this.queryYears = res.data.map( row=> row.year);

							var dom = document.getElementById('container');
							var myChart = echarts.init(dom, null, {
								renderer: 'canvas',
								useDirtyRect: false
							});
							option = {
								xAxis: {
									type: 'category',
									// map( year=>year+'年') ==> 追加汉字年
									data: this.queryYears.map( year=>year+'年')
								},
								yAxis: {
									type: 'value'
								},
								series: [
									{
										data: this.sales,
										type: 'bar',
										showBackground: true,
										backgroundStyle: {
											color: 'rgba(180, 180, 180, 0.2)'
										}
									}
								]
							};
							if (option && typeof option === 'object') {
								myChart.setOption(option);
							}
							window.addEventListener('resize', myChart.resize);
						})
					}
				}
			})
		</script>
	</body>
</html>

<style>
	html,
	body,
	#app {
		height: 100%;
		padding: 0px;
		margin: 0px;
		overflow: hidden;
		color: #333;
	}

	#app {
		/* padding: 50px; */
		box-sizing: border-box;
	}
</style>
